#include "common.h"

#define TOLOWER(x) ((x) | 0x20)

static int Isxdigit(char ch)
{
    return (ch >= '0') && (ch <= '9');
}

static u32 simple_guess_base(const char *cp)
{
    if (cp[0] == '0')
    {
        if (TOLOWER(cp[1]) == 'x' && Isxdigit(cp[2]))
            return 16;
        else
            return 8;
    }
    else
    {
        return 10;
    }
}

u32 simple_strtoul(const char *cp, char **endp, u32 base, u32 *err)
{
    u32 result = 0;
    u32 charnum = 0;

    if (!base)
        base = simple_guess_base(cp);

    if (base == 16 && cp[0] == '0' && TOLOWER(cp[1]) == 'x')
        cp += 2;

    while (Isxdigit(*cp))
    {
        u32 value;

        value = isdigit(*cp) ? *cp - '0' : TOLOWER(*cp) - 'a' + 10;
        if (value >= base)
            break;
        result = result * base + value;
        cp++;
        charnum++;
    }
    if((*cp != '\0') || (charnum > 8))
    {
        *err = 1;
    }

    if (endp)
        *endp = (char *)cp;
    return result;
}





s32 simple_strtol(const char *cp, char **endp, u32 base)
{
    u32 ulCheckerr = 0;
    if(*cp == '-')
        return -simple_strtoul(cp + 1, endp, base, &ulCheckerr);
    return simple_strtoul(cp, endp, base, &ulCheckerr);
}


